import React, {Component, Fragment} from "react";
import {
    GameInfoContent,
    GameResourceContent,
    HeadBackgroundBox,
    HeadBackgroundImage,
    HeadContent,
    Resource,
    ResourceBody,
    VideoContainer
} from "@/common/container/gameContainer/style";
import {GlobalOutlined} from '@ant-design/icons';
import {Col, Image, Popconfirm, Rate, Row, Tooltip} from "antd";
import PropTypes from 'prop-types';
import {queryState, successMsg, writeClip} from "@/util/global";
import Config from '@/config'
import Button from "antd/es/button";
import _ from "lodash";
import {obtainResourceByGid} from "@/api/JustGameCloud";
import {BilibiliVideoList} from "@/api/ThirdPartyApi";
import {buyGame} from "@/api/SysStationOrder";
import {resetUserInfo} from "@/util/UserUtil";
import {isLogin} from "@/util/global";
class Header extends Component {
    constructor(props) {
        super(props);
        this.getResource = this.getResource.bind(this);
        this.makeSureToPay = this.makeSureToPay.bind(this);
        this.state = {
            isLogin: !_.isEmpty(queryState('user.userid')),
            selectPlatform: null,
            platformDistinct: {},
            cloudResource: [],
            /* 0 = 图片  1 = 视频 */
            mediaType: 0,
            BVideo: []
        }
    }

    componentDidMount() {
        const {platformKeys} = this.props.data;
        const {platformDistinct} = this.state;
        if (platformKeys && platformKeys.length > 0) {
            platformKeys.forEach(key => {
                this.props.data.platformList.forEach(item => {
                    if (item.name === key) {
                        if (!platformDistinct[key]) {
                            platformDistinct[key] = "";
                        }
                        if (platformDistinct[key].length === 0) {
                            platformDistinct[key] += "系统版本：" + item.version;
                        } else {
                            platformDistinct[key] += " / " + item.version;
                        }
                    }
                })
            })
        }
        if (this.props.data.hasBought === 1) {
            this.getResource()
        }
        if (!this.props.data.videoUrl) {
            BilibiliVideoList(`${this.props.data.cnName}`)
                .then(res => {
                    this.setState({
                        BVideo: res.data.data.result[10].data
                    })
                })
        }
        this.setState({
            platformDistinct
        })
    }

    getResource() {
        if(isLogin()){
            obtainResourceByGid(this.props.data.id).then(res => {
                if (res.success) {
                    if (!res.data || res.data.length === 0) {
                        successMsg("暂无相关资源，抱歉啦！");
                        return;
                    }
                    this.setState({
                        cloudResource: res.data
                    })
                    successMsg("已获取最新游戏资源信息！");
                }
            })
        }
    }

    makeSureToPay() {
        buyGame(this.props.data.id).then(res => {
            if (res.success) {
                successMsg("购买成功!");
                /* 刷新用户信息 */
                resetUserInfo();
                this.props.reload();
            }
        })
    }

    render() {
        const {data, changeScore} = this.props;


        return <>
            <HeadBackgroundBox>
                <HeadBackgroundImage imageUrl={data.images}/>
            </HeadBackgroundBox>
            <HeadContent>
                <div className={'left'}>
                    <Image width={'100%'}
                           preview={false}
                           height={'100%'}
                           style={{
                               width: '100%',
                               height: '100%'
                           }}
                           src={data.images}/>
                </div>
                <div className={'right'}>
                    <GameResourceContent>
                        <Resource>
                            <ResourceBody>
                                {
                                    data.videoUrl ?
                                        <>
                                            <VideoContainer>
                                                <video style={{
                                                    width: '100%',
                                                    float: 'left',
                                                    height: '100%',
                                                    margin: '0 auto',
                                                    objectFit: 'fill'
                                                }}
                                                       loop
                                                       controls>
                                                    <source src={data.videoUrl} type="video/mp4"/>
                                                </video>
                                                <div className={'about'}>

                                                </div>
                                            </VideoContainer>
                                        </>
                                        :
                                        <>
                                            <VideoContainer>
                                                {
                                                    this.state.BVideo.length > 0 ?
                                                        <iframe
                                                            src={`//player.bilibili.com/player.html?aid=${this.state.BVideo[0].aid}&amp;bvid=${this.state.BVideo[0].bvid}&amp;page=1`}
                                                            id={'ifm'}
                                                            scrolling="no"
                                                            frameBorder="no"
                                                            allowFullScreen={true}
                                                            style={{width: "100%", height: '100%', float: 'left'}}/>
                                                        :
                                                        <iframe src={`//player.bilibili.com/player.html`}
                                                                id={'ifm'}
                                                                scrolling="no"
                                                                frameBorder="no"
                                                                allowFullScreen={true}
                                                                style={{width: "100%", height: '100%', float: 'left'}}/>
                                                }
                                            </VideoContainer>
                                        </>
                                }
                            </ResourceBody>
                        </Resource>
                    </GameResourceContent>
                    <GameInfoContent>
                        <div className={'title'}>
                                    <span className={'chinese-name'}>{` ${data.cnName}`}
                                        <br/>
                                    <span className={'english-name'}>{`${data.enName}`}</span>
                                    </span>
                            <span className={'totalScore'}>
                                        {
                                            data.score === 0 && data.rateCount === 0 ?
                                                <em className={'no-score'}>暂无评分</em>
                                                :
                                                <>
                                                    {
                                                        data.score.toString().indexOf('.') !== -1 ?
                                                            <>
                                                                <em className={'int'}>{data.score.toString().split(".")[0]}</em>
                                                                <em className={'point'}>.</em>
                                                                <em className={'float'}>{data.score.toString().split(".")[1]}</em>
                                                            </> :
                                                            <>
                                                                <em className={'int'}>{data.score}</em>
                                                                <em className={'point'}>.</em>
                                                                <em className={'float'}>0</em>
                                                            </>
                                                    }
                                                </>
                                        }
                                    </span>
                        </div>
                        <div className={'company'}>
                            发行公司：{data.companyName}
                        </div>
                        <div className={'type'}>
                            游戏类型：{
                            data.typeList.length > 0 ?
                                data.typeList.map((type, index) => {
                                    return <Fragment key={type}>
                                    <span style={{marginRight: '5px'}}>
                                        {type}
                                    </span>
                                        <span style={{marginRight: '5px'}}>
                                        {data.typeList.length > index + 1 ? "/" : null}
                                    </span>
                                    </Fragment>
                                })
                                : "暂无"
                        }
                        </div>
                        <div className={'platform'}>
                            游戏平台：{
                            data.platformKeys ?
                                data.platformKeys.map((key, index) => {
                                    return <Fragment key={key}>
                                        <Tooltip placement="topLeft" title={this.state.platformDistinct[key]}>
                                    <span style={{marginRight: '5px'}}>
                                        {key}
                                    </span>
                                            <span style={{marginRight: '5px'}}>
                                        {data.platformKeys.length > index + 1 ? "/" : null}
                                    </span>
                                        </Tooltip>
                                    </Fragment>
                                })
                                : "暂无"
                        }
                        </div>
                        <div className={'time'}>
                            上架日期：{data.time}
                        </div>
                        <div className={'score'}>
                            {data.isScore ? '玩家' : '我要'}评分：<Rate value={data.score} style={{fontSize: '15px'}}
                                                                 onChange={changeScore}
                                                                 disabled={!this.state.isLogin || data.isScore}/>
                            <span className={'rateCount'}>
                        {
                            this.state.isLogin ?
                                <>
                                    {data.rateCount}人参与评分
                                </>
                                :
                                <>
                                    （ 登陆后可打分 ）
                                </>
                        }</span>
                        </div>
                        <div className={'website'}>
                            官方网站：
                            <a onClick={() => window.open(data.website)}><GlobalOutlined/> 点击跳转</a>
                        </div>
                        <div className={'source'}
                             style={this.state.cloudResource && this.state.cloudResource.length > 0 ? {background: 'none'} : null}>
                            <Row className={'row'}>
                                {
                                    !this.state.isLogin ?
                                        /* 未登录状态下 */
                                        <Col className={'col'} span={24}>
                                            <span className={'free-text'}>
                                                <Config.IconFont type={'icon-wancheng'} style={{fontSize: '16px'}}/>
                                                &nbsp;当前游戏&nbsp;<a>登录</a>&nbsp;后可免费下载
                                            </span>
                                        </Col> :
                                        data.cost === 0 ?
                                            /* 是免费游戏 */
                                            <Col className={'col'} span={24}>
                                            <span className={'free-text'}><Config.IconFont type={'icon-wancheng'}
                                                                                           style={{fontSize: '16px'}}/> 当前游戏为免费资源，
                                                <a onClick={this.getResource}>点击此处</a>获取。</span>
                                            </Col>
                                            :
                                            /* 不是免费游戏，判断是否已购买 */
                                            data.hasBought === 0 ?
                                                /* 未购买 */
                                                <Col className={'col'} span={24}>
                                                    该资源下载需要 <span className={'price'}>{data.cost}</span> 枚
                                                    <Config.IconFont type={'icon-jinbi'} style={{fontSize: '20px'}}/>
                                                    <p className={'prompt'}>
                                                        （ 购买后可在3年内无限制下载 ）
                                                    </p>
                                                    <p className={'btn'}>
                                                        <Row gutter={[10, 10]}>
                                                            <Col span={6}/>
                                                            <Col span={6}>
                                                                <Popconfirm
                                                                    placement="topRight"
                                                                    title={"是否确定确定支付？"}
                                                                    onConfirm={this.makeSureToPay}
                                                                    okText="Yes"
                                                                    cancelText="No"
                                                                >
                                                                    <Button type="primary"
                                                                            shape="round"
                                                                            size={"small"} style={{
                                                                        backgroundColor: "#ffb400",
                                                                        border: 'none'
                                                                    }}
                                                                    >
                                                                        JCoin支付
                                                                    </Button>
                                                                </Popconfirm>
                                                            </Col>
                                                            <Col span={6}>
                                                                <Tooltip placement="top"
                                                                         title={`支付金额为 ${data.cost * 0.1} 元`}>
                                                                    <Button type="primary"
                                                                            shape="round"
                                                                            size={"small"} style={{
                                                                        backgroundColor: "#04BE02",
                                                                        border: 'none'
                                                                    }}>
                                                                        微信支付
                                                                    </Button>
                                                                </Tooltip>
                                                            </Col>
                                                            <Col span={6}/>
                                                        </Row>
                                                    </p>
                                                </Col>
                                                :
                                                /* 已购买并且已经获取到了游戏资源信息 */
                                                this.state.cloudResource && this.state.cloudResource.length > 0 ?
                                                    <>
                                                        {
                                                            this.state.cloudResource.map(resource => {
                                                                return <Col className={'resource-title'} span={24}
                                                                            key={resource.title}>
                                                                    {
                                                                        resource.title
                                                                    }
                                                                    <Col className={'resource-content'} span={24}>
                                                                        <Button className={'path'} size={"small"}
                                                                                onClick={() => writeClip(resource.path)}>
                                                                            <Config.IconFont type={'icon-lianjie'}
                                                                                             style={{}}/>网盘地址
                                                                        </Button>
                                                                        <Button className={'secretKey'} size={"small"}
                                                                                onClick={() => writeClip(resource.secretKey)}>
                                                                            <Config.IconFont type={'icon-yuechi'}
                                                                                             style={{fontSize: '15px'}}/>提取码
                                                                        </Button>
                                                                    </Col>
                                                                </Col>
                                                            })
                                                        }
                                                    </>
                                                    :
                                                    /* 已购买并且但未获取到游戏资源信息 */
                                                    <Col className={'col'} span={24}>
                                                    <span className={'free-text'}>
                                                        <Config.IconFont type={'icon-wancheng'}
                                                                         style={{fontSize: '16px'}}/> 当前游戏您已购买，
                                                        <a onClick={this.getResource}>点击此处</a>获取。</span>
                                                    </Col>
                                }
                            </Row>
                        </div>
                    </GameInfoContent>
                </div>
            </HeadContent>
        </>
    }
}

Header.propTypes = {
    data: PropTypes.object,
    changeScore: PropTypes.func,
    reload: PropTypes.func
}
export default Header;
